package com.lagou.client;

import com.lagou.client.UserClientHandler;
import com.google.common.base.Stopwatch;
import com.lagou.utils.JSONDerializer;
import com.lagou.utils.JSONSerializer;
import com.lagou.utils.RpcEncoder;
import com.lagou.utils.RpcDecoder;
import com.lagou.request.RpcRequest;
import com.lagou.response.RpcResponse;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.internal.StringUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.Log4JLoggerFactory;

import java.util.concurrent.*;


public class RpcConsumer {
    private static final InternalLogger logger = Log4JLoggerFactory.getInstance(RpcConsumer.class);

    /**
     * 请求执行线程池
     */
    private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    /**
     * 定时执行线程池
     */
    private ScheduledExecutorService schedulerExecutor = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());

    private EventLoopGroup group;

    private ScheduledFuture<?> schedule;

    private UserClientHandler userClientHandler;

    private String address;

    private Integer port;

    /**
     * 最近响应时间
     */
    private Long lastResponseTimeSpan = 0L;

    /**
     * 上次请求时间
     */
    private Long lastRequestTime;

    public Long getLastResponseTimeSpan() {
        return lastResponseTimeSpan;
    }

    public RpcConsumer(String address, Integer port) {
        this.address = address;
        this.port = port;
        userClientHandler = new UserClientHandler();
        try {
            initClient();
        } catch (InterruptedException e) {
            logger.error("初始化客户端失败");
            throw new IllegalStateException("RpcConsumer init error");
        }
    }

    /**
     * 初始化客户端
     */
    public void initClient() throws InterruptedException {
        if (StringUtil.isNullOrEmpty(address) || port == null) {
            throw new IllegalArgumentException("address or port can't be null");
        }

        group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new RpcDecoder(RpcResponse.class, new JSONDerializer()));
                        pipeline.addLast(userClientHandler);
                    }
                });

        bootstrap.connect(address, port).sync();
    }

    /**
     * 关闭socket连接
     */
    public void shutdown() {
        if (group != null && !group.isShutdown()) {
            group.shutdownGracefully();
        }
    }

    /**
     * 远程调用
     *
     * @param rpcRequest
     * @return
     */
    public Object invoke(RpcRequest rpcRequest) {
        userClientHandler.setRequest(rpcRequest);
        System.out.println("调用服务端地址：" + address + ":" + port);
        try {
            Stopwatch stopwatch = Stopwatch.createStarted();
            lastRequestTime = System.currentTimeMillis();
            Object result = executor.submit(userClientHandler).get(1000, TimeUnit.MILLISECONDS);
            lastResponseTimeSpan = stopwatch.stop().elapsed(TimeUnit.MILLISECONDS);
            if (schedule != null) {
                schedule.cancel(true);
            }
            schedule = schedulerExecutor
                    .schedule(new ClearUpResponseTimeTask(this), 5000, TimeUnit.MILLISECONDS);
            return result;
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            e.printStackTrace();
            throw new RuntimeException("call error");
        }
    }

    /**
     * 清零请求时间task
     */
    public static class ClearUpResponseTimeTask implements Runnable {

        private RpcConsumer rpcConsumer;

        public ClearUpResponseTimeTask(RpcConsumer rpcConsumer) {
            this.rpcConsumer = rpcConsumer;
        }

        @Override
        public void run() {
            long millSecondTimespan = System.currentTimeMillis() - rpcConsumer.lastRequestTime;
            if (millSecondTimespan > 5000) {
                rpcConsumer.lastResponseTimeSpan = 0L;
                System.out.println(rpcConsumer.address + ":" + rpcConsumer.port + "清零响应时间");
            }
        }
    }

}
